package com.hwadee.teachingprocessmanagementsystem.service.teacher.impl;

import com.hwadee.teachingprocessmanagementsystem.dao.ApplicationFormDao;
import com.hwadee.teachingprocessmanagementsystem.dao.CourseChangeRequestDao;
import com.hwadee.teachingprocessmanagementsystem.dto.DepartmentDto;
import com.hwadee.teachingprocessmanagementsystem.dto.MajorDto;
import com.hwadee.teachingprocessmanagementsystem.dto.student.StudentCourseChangeDto;
import com.hwadee.teachingprocessmanagementsystem.dto.student.StudentCourseInfoDto;
import com.hwadee.teachingprocessmanagementsystem.dto.student.StudentCoursewareDto;
import com.hwadee.teachingprocessmanagementsystem.dto.teacher.*;
import com.hwadee.teachingprocessmanagementsystem.entity.*;
import com.hwadee.teachingprocessmanagementsystem.service.base.*;
import com.hwadee.teachingprocessmanagementsystem.service.teacher.TeacherService;
import com.hwadee.teachingprocessmanagementsystem.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author LINKE
 * @ProjectName:teaching-process-management-system-back
 * @Title: TeacherServiceImpl
 * @Package com.hwadee.teachingprocessmanagementsystem.service.teacher.impl
 * @Description: 教师服务接口实现
 * @date 2024/7/14 23:22
 */

@Service("TeacherService")
public class TeacherServiceImpl implements TeacherService {
    @Autowired
    private StudentService studentService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private MajorService majorService;
    @Autowired
    private ClassroomService classroomService;
    @Autowired
    private CourseClassesService courseClassesService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private CampusService campusService;
    @Autowired
    private ExamResultService examResultService;
    @Autowired
    private com.hwadee.teachingprocessmanagementsystem.service.base.TeacherService teacherService;
    @Autowired
    private ExamScheduleService examScheduleService;
    @Autowired
    private AssessmentMethodService assessmentMethodService;
    @Autowired
    private ApplicationFormService applicationFormService;
    @Autowired
    private CourseChangeRequestService courseChangeRequestService;
    @Autowired
    private com.hwadee.teachingprocessmanagementsystem.service.student.StudentService studentService2;

    /**
     * 获取考核方式数据
     *
     * @param
     * @return 教师考核方式列表
     */
    public TeacherAssessmentMethodDto getAssessmentMethodDto(){
        TeacherAssessmentMethodDto teacherAssessmentMethodDto = new TeacherAssessmentMethodDto();
        List<AssessmentMethod> assessmentMethodsList= this.assessmentMethodService.queryAll();

        System.out.println(assessmentMethodsList);
        for (AssessmentMethod assessmentMethod : assessmentMethodsList) {
            Integer assessmentMethodId = assessmentMethod.getMethodId();
            String name = assessmentMethod.getName();
            String description = assessmentMethod.getDescription();
            teacherAssessmentMethodDto.addTeacherAssessmentMethod(assessmentMethodId,name,description);
        }

        System.out.println(teacherAssessmentMethodDto);
        return teacherAssessmentMethodDto;
    }

    @Override
    public StudentCourseChangeDto getStudentCourseChangeDto(Teacher teacher) {
        StudentCourseChangeDto studentCourseChangeDto = new StudentCourseChangeDto();
        List<Course> courseList = this.courseService.queryByTeacherId(teacher);
        courseList.forEach(item -> {
            Integer courseLeaderId = item.getCourseLeaderId();
            Teacher teacher1 = this.teacherService.queryById(courseLeaderId);
            String teacherName = teacher1.getName();
            Integer teacherId = teacher1.getTeacherId();
            String courseId = item.getCourseId();
            String courseName = item.getName();
            studentCourseChangeDto.addCourseTeacherInfo(courseId, courseName, String.valueOf(teacherId), teacherName);
        });
        List<CourseChangeRequest> courseChangeRequests = this.courseChangeRequestService.queryAllByTeacherId(teacher);
        studentCourseChangeDto.setCourseChangeRequestList(courseChangeRequests);
        return studentCourseChangeDto;
    }

    /**
     * 获取教师考试数据统计Dto
     *
     * @param courseId
     * @return 教师考试数据统计Dto
     */
    @Override
    public TeacherDataStatisticsDto getTeacherDataStatistics(String courseId) {
        TeacherDataStatisticsDto teacherDataStatisticsDto = new TeacherDataStatisticsDto();

        // 查询课程考试号
        Integer examId = this.examScheduleService.queryByCourseId(courseId).getExamId();
        String type = this.courseService.queryById(courseId).getType();
        String courseName = this.courseService.queryById(courseId).getName();

        //查询考试成绩
        List<ExamResult> examResultList = this.examResultService.queryByExamId(examId);

        for (ExamResult examResult : examResultList) {
            String studentNumber = examResult.getStudentNumber();
            String studentName = this.studentService.queryByStudentNumber(studentNumber).getName();
            try {
                Double score = Double.parseDouble(examResult.getScore().toString());
                Integer grade = score.intValue();
                teacherDataStatisticsDto.addTeacherDataStatistics(studentNumber, studentName, type, courseName, grade);
            } catch (NumberFormatException e) {
                // 处理转换异常，例如记录日志或返回错误信息
                e.printStackTrace();
            }
        }

        return teacherDataStatisticsDto;
    }

    /**
     * 获取教师人才培养方案页面Dto，显示全部专业
     *
     * @param
     * @return
     */
    @Override
    public TeacherTalentPlanDto getTeacherTalentPlanDto() {
        TeacherTalentPlanDto teacherTalentPlanDto = new TeacherTalentPlanDto();
        DepartmentDto  departmentDto = this.departmentService.getDepartmentDto();
        MajorDto majorDto = this.majorService.getMajorDto();

        teacherTalentPlanDto.setDepartmentDto(departmentDto);
        teacherTalentPlanDto.setMajorDto(majorDto);

        // 查询所有专业信息
        List<Major> majorList= this.majorService.queryAll();
        for(Major major : majorList){
            String majorCode = major.getMajorId().toString();
            String departmentId = major.getDepartmentId();
            Department department = this.departmentService.queryById(departmentId);
            String departmentName = department.getName();
            String majorName = major.getName();
            String teachingPlan = major.getTeachingPlan();
            teacherTalentPlanDto.addTeacherTalentPlan(majorCode,majorName, teachingPlan,departmentName);
        }
        return teacherTalentPlanDto;
    }

    /**
     * 获取教师人才培养方案页面Dto，查询范围为全部专业
     *
     * @param department
     * @param majorName
     * @return
     */
    @Override
    public TeacherTalentPlanDto getTeacherTalentPlanDto(String department, String majorName) {
        TeacherTalentPlanDto teacherTalentPlanDto = new TeacherTalentPlanDto();
        DepartmentDto departmentDto = this.departmentService.getDepartmentDto();
        MajorDto majorDto = this.majorService.getMajorDto();
        teacherTalentPlanDto.setDepartmentDto(departmentDto);
        teacherTalentPlanDto.setMajorDto(majorDto);

        // 查询所有专业信息
        List<Major> majorList = this.majorService.queryAll();

        //遍历所有专业信息，查询教师所选培养方案
        for (Major major : majorList) {
            // 查询教师所选专业
            String departmentId = major.getDepartmentId();
            String majorId = major.getMajorId().toString();

            //指定了系部
            if (!Objects.equals(department, "null") && !department.isEmpty()) {
                //指定了专业
                if (!Objects.equals(majorName, "null") && !majorName.isEmpty()) {
                    if (majorName.equals(major.getName())) {

                        Department department1 = this.departmentService.queryById(departmentId);
                        String departmentName = department1.getName();
                        String teachingPlan = major.getTeachingPlan();

                        teacherTalentPlanDto.addTeacherTalentPlan(majorId, majorName, teachingPlan, departmentName);
                        return teacherTalentPlanDto;
                    }
                }

                Department department1 = this.departmentService.queryById(departmentId);
                String departmentName = department1.getName();
                // 查询教师所选系部
                if (department.equals(departmentName)){
                    String majorName2 = major.getName();
                    String teachingPlan = major.getTeachingPlan();
                    teacherTalentPlanDto.addTeacherTalentPlan(majorId, majorName2, teachingPlan, departmentName);
                    return teacherTalentPlanDto;
                }
            }
        }

        return teacherTalentPlanDto;
    }

    /**
     * 获取教师课程信息页面Dto
     *
     */
    @Override
    public TeacherScheduleInfoDto getTeacherScheduleInfo(Teacher teacher) {
        TeacherScheduleInfoDto teacherScheduleInfoDto = new TeacherScheduleInfoDto();

        // 查询教师所有课程
        Course course= this.courseService.queryByTeacherId(teacher.getTeacherId().toString());

            String courseId = course.getCourseId();
            /**
             * 根据课程ID查询课程名
             */
            String courseName = course.getName();

            List<CourseClasses> courseClassesList= this.courseClassesService.queryAllByCourseId(courseId);

            for (CourseClasses courseClasses : courseClassesList) {
            Integer classroomId = courseClasses.getClassroomId();

            /**
             * 根据教室ID查询教室位置
             */
            Classroom classroom = this.classroomService.queryById(classroomId);
            Integer campusId = classroom.getCampusId();
            Campus campus = this.campusService.queryById(campusId);
            String campusName = campus.getName();


            Teacher leaderteacher = this.teacherService.queryById(teacher.getTeacherId());

            String teacherName = leaderteacher.getName();
            String location = classroom.getName();
            String weeks = courseClasses.getWeeks();
            String date = courseClasses.getDate();
            String time = courseClasses.getTime();

            teacherScheduleInfoDto.addScheduleInfo(courseName, weeks, date, time, teacherName, campusName, location);
            }
        System.out.println(teacherScheduleInfoDto);
        return teacherScheduleInfoDto;
    }

    /**
     * 获取教师课程标准页面Dto
     * @param teacher
     * @return
     */
    @Override
    public TeacherCourseStandardDto getTeacherCourseStandardDto(Teacher teacher) {
        // 查询教师所有课程
        System.out.println("***************************************");
        System.out.println(teacher.getTeacherId());
        Course course= this.courseService.queryByTeacherId(teacher.getTeacherId().toString());
        String courseId = course.getCourseId();

        TeacherCourseStandardDto teacherCourseStandardDto = new TeacherCourseStandardDto();
        DepartmentDto departmentDto = this.departmentService.getDepartmentDto();
        teacherCourseStandardDto.setDepartmentDto(departmentDto);


            Integer majorId = course.getMajorId();
            Major major = this.majorService.queryById(majorId);
            String departmentId = major.getDepartmentId();
            Department department = this.departmentService.queryById(departmentId);
            String departmentName = department.getName();
            String courseName = course.getName();
            Integer classHour = course.getClassHour();
            Integer credits = course.getCredits();
            String type = course.getType();
            teacherCourseStandardDto.addTeacherCourseStandard(departmentName, courseId, courseName, classHour, credits, type);
        System.out.println(teacherCourseStandardDto);
            return teacherCourseStandardDto;
    }

    @Override
    public TeacherCoursewareDto getTeacherCoursewareDto(Teacher teacher) throws IOException {
        TeacherCoursewareDto teacherCoursewareDto = new TeacherCoursewareDto();
        // 获取教师的课程信息
        List<Course> courseList = this.courseService.queryByTeacherId(teacher);
        teacherCoursewareDto.setTeacherCourseList(courseList);
        // 获取文件列表和目录列表
        // 遍历教师课程编号
        for (Course course : courseList) {
            String courseId = course.getCourseId();
            String courseName = course.getName();
            Integer courseLeaderId = course.getCourseLeaderId();
            String teacherName = this.teacherService.queryById(courseLeaderId).getName();
            // 对每个课程编号查找目录下文件和子目录
            Map<String, List<File>> map = FileUtils.listFiles(new File("src/main/resources/static/courseware/"+courseId));
            List<File> fileList = new ArrayList<File>();
            List<File> pathList = new ArrayList<File>();
            if (map != null) {
                fileList = map.get("files");
                pathList = map.get("paths");
            }
            if (!fileList.isEmpty()) {
                for (File file : fileList) {
                    teacherCoursewareDto.addFileInfo(
                            file.getName(),
                            file.length() / (1024),
                            String.valueOf((new Date(file.lastModified())).getTime()),
                            courseName,
                            teacherName,
                            file.getParentFile().getName()
                    );
                }
            }
            if (!pathList.isEmpty()) {
                for (File file : pathList) {
                    teacherCoursewareDto.addPathInfo(
                            file.getName(),
                            String.valueOf((new Date(file.lastModified())).getTime()),
                            courseName,
                            file.getParentFile().getName()
                    );
                }
            }
        }
        return teacherCoursewareDto;
    }
}